package edu.uoc.tds.pec4.server;



import java.awt.EventQueue;
import java.awt.Toolkit;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.UIManager;

import edu.uoc.tds.pec4.server.impl.MantenimientoInterfaceImpl;
import edu.uoc.tds.pec4.server.impl.GestionAcademicaInterfaceImpl;
import edu.uoc.tds.pec4.server.impl.ConexionMatriculaInterfaceImpl;

import edu.uoc.tds.pec4.client.PanelConexionUI;
import edu.uoc.tds.pec4.client.PanelMenusUI;
import edu.uoc.tds.pec4.i18n.TDSLanguageUtils;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import javax.swing.JLabel;

public class Servidor extends JFrame {

	/** 
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static boolean registroInicial = false;
	private JPanel contentPane;
	private boolean status = false;
	private MantenimientoInterfaceImpl mantenimientoInterfaceImpl = null;
	private GestionAcademicaInterfaceImpl gestionAcademicaInterfaceImpl = null;
	private ConexionMatriculaInterfaceImpl conexionMatriculaInterfaceImpl = null;
	private final String url1 = new String("//localhost/TURVA1");
 	private final String url2 = new String("//localhost/TURVA2");
	private final String url3 = new String("//localhost/TURVA3");
	private JLabel lblPendienteIniciarServidor;
	private JButton btnIniciarServidor;
	private JButton btnDetenerServidor;
	private Registry registry;
	

        /**
         * Launch the application.
         */
        public static void main(String[] args) {
                EventQueue.invokeLater(new Runnable() {
                        public void run() {
                                try {
                                        Servidor frame = new Servidor();
                                        frame.setVisible(true);
                                } catch (Exception e) {
                                        e.printStackTrace();
                                }
                        }
                });
        }

        /**
         * Create the frame.
         */
        public Servidor() {
               
                boolean existeFicheroMensajes = TDSLanguageUtils.setDefaultLanguage("i18n/ES_messages");
                if (!existeFicheroMensajes) {
                        JOptionPane.showMessageDialog(null, "ERROR: no se encuentra el fichero 'i18n/ES_message.properties'.\nCorrija el error y vuelva a intentarlo","error.general",0);
                        System.exit(-1); //abandonamos la aplicacin se trata de un error grave

                }
               
               
                setBackground(UIManager.getColor("EditorPane.selectionBackground"));
                setTitle(TDSLanguageUtils.getMessage("servidor.titulo"));
                setIconImage (Toolkit.getDefaultToolkit().getImage(PanelConexionUI.class.getResource("LogoTurva.gif")));
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                setBounds(100, 100, 570, 270);
                contentPane = new JPanel();
                contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
                setContentPane(contentPane);
                contentPane.setLayout(null);
               
                lblPendienteIniciarServidor = new JLabel(TDSLanguageUtils.getMessage("servidor.pendienteRegistroRMI"));
                lblPendienteIniciarServidor.setBounds(17, 17, 493, 16);
                contentPane.add(lblPendienteIniciarServidor);
               
                btnIniciarServidor = new JButton(TDSLanguageUtils.getMessage("servidor.iniciar"));
                btnIniciarServidor.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent arg0) {
                                if(status == false)
                                        try {
                                                iniciarServidor(1099);
                                        } catch (RemoteException e) {
                                        	JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("cliente.error.conectar"), TDSLanguageUtils.getMessage("cliente.error.titulo"), 0);
                                                e.printStackTrace();
                                        }
                        }
                });
                btnIniciarServidor.setBounds(160, 90, 172, 40);
                contentPane.add(btnIniciarServidor);
               
                btnDetenerServidor = new JButton(TDSLanguageUtils.getMessage("servidor.detener"));
                btnDetenerServidor.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                                if(status == true)
                                        try {
                                                pararServidor();
                                        } catch (RemoteException e1) {
                                                // TODO Auto-generated catch block
                                                e1.printStackTrace();
                                        }
                        }
                });
                btnDetenerServidor.setBounds(365, 90, 172, 40);
                contentPane.add(btnDetenerServidor);
                
                JLabel labelLogo = new JLabel("");
    			labelLogo.setBounds(17, 45, 148, 159);
    			labelLogo.setIcon(new ImageIcon(PanelMenusUI.class.getResource("LogoInicio.png")));
    			contentPane.add(labelLogo);
               
                }



        private void pararServidor()  throws RemoteException {
               boolean pararServer = true; 
               
        		try {
        			if (gestionAcademicaInterfaceImpl.numeroRecuentos()>0)
            	    {
            		   if(JOptionPane.showConfirmDialog (null, gestionAcademicaInterfaceImpl.numeroRecuentos()+" "+TDSLanguageUtils.getMessage("servidor.recuentos.detener"),TDSLanguageUtils.getMessage("servidor.detener"), JOptionPane.OK_CANCEL_OPTION)==JOptionPane.OK_OPTION) 
            		      pararServer=true;
            		      else
            		    	 pararServer=false;
            	    }
        		  if (pararServer==true)
        		  {
                        Naming.unbind(url1);
                        Naming.unbind(url2);
                        Naming.unbind(url3);
                        //registry.unbind(url);
                   status = false;
                   gestionAcademicaInterfaceImpl.borraListaRecuentos();
                   btnIniciarServidor.setEnabled(true);
                   btnDetenerServidor.setEnabled(false);
                   lblPendienteIniciarServidor.setText(TDSLanguageUtils.getMessage("servidor.pendienteRegistroRMI"));
        		  }
                }catch (Exception e) {          
                        //No se ha podido enlazar con RMI
                        //e.printStackTrace();
                        JOptionPane.showMessageDialog(null, e.getMessage()+TDSLanguageUtils.getMessage("servidor.servicio.noCargado"),TDSLanguageUtils.getMessage("error.general"),0);
                        System.exit(-1); //abandonamos la aplicacin se trata de un error grave

                }
        }


	private void iniciarServidor(int numPuertoRMI) throws RemoteException   {
		 
		 registry=LocateRegistry.getRegistry();
		 if(registroInicial == false){
			 registry=LocateRegistry.createRegistry(numPuertoRMI);
			 registroInicial = true;
		 }
			 try{
				    if(mantenimientoInterfaceImpl == null)
				    	mantenimientoInterfaceImpl = new MantenimientoInterfaceImpl();
        			if(gestionAcademicaInterfaceImpl == null)
        				gestionAcademicaInterfaceImpl = new GestionAcademicaInterfaceImpl();
        			if(conexionMatriculaInterfaceImpl == null)
        				conexionMatriculaInterfaceImpl = new ConexionMatriculaInterfaceImpl();        			
        			
        		}catch (Exception e){
        			e.printStackTrace();
        			JOptionPane.showMessageDialog(null, e.getMessage()+TDSLanguageUtils.getMessage("error.registroRMI"),TDSLanguageUtils.getMessage("error.general"),0);
        			System.exit(-1); //abandonamos la aplicaci�n se trata de un error grave	
        		}
                
                try {
                	 Naming.rebind(url1,mantenimientoInterfaceImpl);
                     Naming.rebind(url2,gestionAcademicaInterfaceImpl);
                     Naming.rebind(url3,conexionMatriculaInterfaceImpl);
                   } catch (MalformedURLException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                     }
                status = true;
                btnIniciarServidor.setEnabled(false);
                btnDetenerServidor.setEnabled(true);
                lblPendienteIniciarServidor.setText(TDSLanguageUtils.getMessage("servidor.servicioRMI.correcto"));
         
                }

}
